package cn.hcbycloud.common.async.config;

import cn.hcbycloud.common.async.service.pool.IThreadPoolService;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author gaoh
 * @desc 自定义异步任务线程池, 异步任务异常捕获处理器
 * @date 2022年02月06日 下午 10:01
 */
@Slf4j
@EnableAsync
@Configuration
@AllArgsConstructor
public class AsyncPoolConfig implements AsyncConfigurer {
    private IThreadPoolService threadPoolService;

    /**
     * 将自定义的线程池注入至spring容器中
     *
     * @return
     */
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = threadPoolService.getThreadPoolProperties();
        if (ObjectUtil.isNull(executor)) {
            executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(30);
            executor.setQueueCapacity(20);
            executor.setKeepAliveSeconds(60);
            // 任务ID的前缀
            executor.setThreadNamePrefix("HcbyCloud-Async-");
        }
        // 等待所有任务结果候再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 定义拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池, 初始化 core 线程
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    @SuppressWarnings("all")
    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

        @Override
        public void handleUncaughtException(Throwable throwable, Method method,
                                            Object... objects) {
            throwable.printStackTrace();
            log.error("Async Error: [{}], Method: [{}], Param: [{}]",
                    throwable.getMessage(), method.getName(),
                    JSON.toJSONString(objects));
            // TODO 发送邮件或者是短信, 做进一步的报警处理
        }
    }

}